import os
import uuid

from dotenv import load_dotenv
from elevenlabs import VoiceSettings
from elevenlabs.client import ElevenLabs

load_dotenv()

ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")

if not ELEVENLABS_API_KEY:
    raise ValueError("ELEVENLABS_API_KEY environment variable not set")

client = ElevenLabs(
    api_key=ELEVENLABS_API_KEY,
)


def text_to_speech_file(
        text: str,
        file_path: str,
        voice_id: str = os.getenv("ELEVENLABS_VOICE_ID")) -> str:
    """
    Converts text to speech and saves the output as an MP3 file at the specified path.

    Args:
        text (str): The text content to convert to speech.
        file_path (str): The full path where the audio file should be saved.
        voice_id (str): The ID of the voice to use. Defaults to "pNInz6obpgDQGcFmaJgB" (Adam).

    Returns:
        str: The file path where the audio file has been saved.
    """
    response = client.text_to_speech.convert(
        voice_id=voice_id,
        optimize_streaming_latency="0",
        output_format="mp3_22050_32",
        text=text,
        model_id="eleven_turbo_v2",
        voice_settings=VoiceSettings(
            stability=0.8,
            similarity_boost=1.0,
            style=0.0,
            use_speaker_boost=True,
        ),
    )

    # 确保目标目录存在
    os.makedirs(os.path.dirname(file_path), exist_ok=True)

    # 写入音频流到文件
    with open(file_path, "wb") as f:
        for chunk in response:
            if chunk:
                f.write(chunk)

    print(f"新的音频文件已成功保存到 {file_path}")

    return file_path


# 示例用法
if __name__ == "__main__":
    text = "read"
    filename = text
    file_path = os.path.join(
        os.path.dirname(
            os.path.dirname(__file__)),
        'static',
        'audio',
        f'{filename}.mp3')
    # 使用默认声音
    text_to_speech_file(text, file_path)
